package main

import (
	"fmt"
	"golang-zinx-demo/yanx/yiface"
	"golang-zinx-demo/yanx/ynet"
)

// ping test自定义路由
type Ping1Router struct {
	ynet.BaseRouter
}

// ping test自定义路由
type Ping2Router struct {
	ynet.BaseRouter
}

// test Handel
func (r *Ping1Router) Handle(request yiface.IRequest) {
	fmt.Println("CallRouter handle")
	// 先读取k客户端的数据，再回写ping...ping...ping...
	fmt.Printf("recv from client:msgID = %d ,data = %s\n",
		request.GetMsgID(), string(request.GetData()))

	err := request.GetConnection().SendMsg(1, []byte("ping1...ping1...ping1..."))
	if err != nil {
		fmt.Println(err)
	}
}

// test Handel
func (r *Ping2Router) Handle(request yiface.IRequest) {
	fmt.Println("CallRouter handle")
	// 先读取k客户端的数据，再回写ping...ping...ping...
	fmt.Printf("recv from client:msgID = %d ,data = %s\n",
		request.GetMsgID(), string(request.GetData()))

	err := request.GetConnection().SendMsg(1, []byte("ping2...ping2...ping2..."))
	if err != nil {
		fmt.Println(err)
	}
}

// 创建链接之前的钩子函数
func DoConnectionBegin(conn yiface.IConnection) {
	fmt.Println("++++=====+++++Call DoConnectionBegin")
	if err := conn.SendMsg(1, []byte("DoConnectionBegin")); err != nil {
		fmt.Println(err)
	}

	// 给当前的链接创建一些属性
	fmt.Println("Set conn name、home、Github...")
	conn.SetProperty("Name", "YanYeek")
	conn.SetProperty("Home", "KM")
	conn.SetProperty("Github", "https://github.com/YanYeek")
}

// 创建链接之后的钩子函数
func DoConnectionAfter(conn yiface.IConnection) {
	defer fmt.Println("*****=====*******Called DoConnectionAfter")
	defer fmt.Println("conn ID = ", conn.GetConnID(), "is lost...")

	if name, err := conn.GetProperty("Name"); err == nil {
		fmt.Println("Name = ", name)
	}
	if home, err := conn.GetProperty("Home"); err == nil {
		fmt.Println("Home = ", home)
	}
	if github, err := conn.GetProperty("Github"); err == nil {
		fmt.Println("Github = ", github)
	}
}

func main() {
	// 1 创建一个server句柄，使用yanx的api
	s := ynet.NewServer("[Server v0.0.1]")

	// 2 注册链接的钩子函数
	s.SetOnConnStart(DoConnectionBegin)
	s.SetOnConnStop(DoConnectionAfter)
	// 3 给当前服务器添加一个自定义的router 路由
	s.AddRouter(1, &Ping1Router{})
	s.AddRouter(2, &Ping2Router{})

	// 3 启动server
	s.Serve()
}
